package cn.le.monitor;

import cn.le.Tool;
import cn.le.mode.FileMode;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;


public class FileOut extends Thread{

	/**
	 * 文件信息保存集合
	 */
	private	 static Map<String,FileMode> filePathMap = new ConcurrentHashMap <String, FileMode>();
	/**修改次数*/
	private static Integer FREQUENCY = 3;
	/**补丁路径*/
	private static String PATCHPATH;
	/**监听路径*/
	private static String MONITORPATH;

	public static void inti()
	{
		PATCHPATH = Tool.load("patchPath").replace("\\", "/")+"/";
		MONITORPATH = Tool.load("monitorPath").replace("\\", "/")+"/";
		FREQUENCY = Integer.parseInt(Tool.load("frequency").toString());
	}

	@Override
	public void run() {

		while (true) {

			for (Map.Entry<String, FileMode> demoMap : filePathMap.entrySet()) {
				FileMode mode = demoMap.getValue();
				//如果修改次数等于了可输入次数就整理输出
				if(mode.getFrequency() > FREQUENCY)
				{
					if(mode.isRemove())
					{
						deleteFile(mode);
						break;
					}
					//修改前的文件名不为空时,删除文件
					if( mode.getOldName() != null)
					{
						deleteFile(mode);
					}
					outFile(mode);
				}
			}
		}
	}

	/**
	 * 添加文件信息
	 * oldName:原名字
	 * newName:新名字
	 * isRemove:是否移除
	 */
	public static void addFile(String oldName, String newName,boolean isRemove)
	{
		//如果不满足类型就不做任何操作
		if(!(newName.contains("src") || newName.contains("WebRoot")))
		{
			return;
		}
		if(!newName.substring(newName.lastIndexOf(".")).matches(".java|.class|.xml|.jsp|.js|.properties|.gif|.png|.css|.jpg|.jar"))
		{
			return;
		}

		//文件整理径路
		String patchPath = (PATCHPATH + newName).replace("\\", "/");
		//检测到修改文件路径
		String rootPaht = (MONITORPATH + newName).replace("\\", "/");
		//切割文件名
		String fileName = patchPath.substring(patchPath.lastIndexOf("/")+1);
		//切割文件路径
		patchPath = patchPath.substring(0,patchPath.lastIndexOf("/")+1);

		int index = 0;
		//如果是重命名
		if(oldName != null)
		{
			//整理修改前文件名的名字
			oldName =  oldName.replace("\\", "/");
			//如果重命名前文件有过修改,清楚记录,并获取修改次数
			FileMode mode = filePathMap.get(PATCHPATH+oldName);
			if( mode != null)
			{
				index = mode.getFrequency();
				filePathMap.remove(PATCHPATH+oldName);
			}
			oldName = oldName.substring(oldName.lastIndexOf("/")+1);
		}

		//整理输出到集合
		FileMode mode = filePathMap.get(patchPath+fileName);
		if(mode == null)
		{
			mode = new FileMode(patchPath,rootPaht,fileName,oldName,isRemove);
		}
		//文件格式如果是图片格式,可直接整理出入
		if(newName.substring(newName.lastIndexOf(".")).matches(".gif|.png|.js|.css|.jpg|.jar") )
		{
			mode.setFrequency(FREQUENCY);
		}
		mode.setFrequency(mode.getFrequency()+1+index);
		mode.setRemove(isRemove);
		filePathMap.put(patchPath+fileName, mode);
		System.out.println("输出:  "+patchPath+fileName);
	}
	/**
	 * 删除文件
	 */
	private static void deleteFile(FileMode mode){
		String file =  mode.getFolderPath()+(mode.getOldName() != null ? mode.getOldName() : mode.getFileName());
		try {
			Files.deleteIfExists(Paths.get(file));
			System.out.println("删除: "+file);
		} catch (IOException e) {
			//e.printStackTrace();
			return;
		}
		//清楚整理集合中的此文件数据
		filePathMap.remove(file);

	}
	/**
	 * 输出文件
	 */
	private static void outFile(FileMode mode)
	{
		//验证此路径是否存在,如不存在创建此目录
		Path path = Paths.get(mode.getFolderPath());
		try {
			if(Files.notExists(path))
			{
				Files.createDirectories(path);
			}
			//把文件copy到整理目录
			Files.copy(Paths.get(mode.getFilePath()),
					new FileOutputStream(mode.getFolderPath()+mode.getFileName()));
		} catch (Exception e) {
			//当文件被占用发生异常时,返回重新输出
			return;
		}
		System.out.println("整理成功   : "+ mode.getFolderPath()+mode.getFileName());
		//文件被输出后,除非再次修改,否则不再被输出
		mode.setFrequency(FREQUENCY);
	}
}
